<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <!-- 账号输入框 -->
                <el-form-item label="账号" prop="account">
                    <el-input v-model="formData.account" :disabled="formData.root == 1" placeholder="请输入账号" clearable />
                </el-form-item>
                <!-- 管理员头像 -->
                <el-form-item label="头像">
                    <div>
                        <div>
                            <material-picker v-model="formData.avatar" :limit="1" />
                        </div>
                        <div class="form-tips">建议尺寸：100*100px，支持jpg，jpeg，png格式</div>
                    </div>
                </el-form-item>

                <!-- 名称输入框 -->
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入名称" clearable />
                </el-form-item>
                <el-form-item label="归属部门" prop="dept_id">
                    <el-tree-select class="flex-1" v-model="formData.dept_id" :data="optionsData.dept" clearable
                        multiple node-key="id" :props="{
                            value: 'id',
                            label: 'name',
                            disabled(data: any) {
                                return data.status !== 1
                            }
                        }" check-strictly :default-expand-all="true" placeholder="请选择上级部门" />
                </el-form-item>
                <el-form-item label="岗位" prop="jobs_id">
                    <el-select class="flex-1" v-model="formData.jobs_id" clearable multiple placeholder="请选择岗位">
                        <el-option v-for="(item, index) in optionsData.jobs" :key="index" :label="item.name"
                            :value="item.id" />
                    </el-select>
                </el-form-item>

                <!-- 角色选择框 -->
                <el-form-item label="角色" prop="role_id" v-if="formData.root != 1">
                    <el-select v-model="formData.role_id" :disabled="formData.root == 1" class="flex-1"
                        placeholder="请选择角色" clearable @change="handleRoleChange">
                        <el-option v-for="(item, index) in optionsData.role" :key="index" :label="item.name"
                            :value="item.id" :data-grade="item.grade" />
                    </el-select>
                </el-form-item>

                <!-- 区域选择器 - 根据角色grade控制 -->
                <el-form-item label="管理区域" prop="province_id" v-if="showAreaSelector">
                    <span style="padding-right: 30px" v-if="mode === 'edit'">{{editArea.province_name}}/{{editArea.city_name}}{{editArea.area_name? `/${editArea.area_name}`: ''}}</span>
                    <area-picker v-model="areaIds" :level="formData.grade"></area-picker>
                </el-form-item>

                <!-- 密码输入框 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="formData.password" show-password clearable placeholder="请输入密码" />
                </el-form-item>

                <!-- 确认密码输入框 -->
                <el-form-item label="确认密码" prop="password_confirm">
                    <el-input v-model="formData.password_confirm" show-password clearable placeholder="请输入确认密码" />
                </el-form-item>

                <!-- 管理员状态 -->
                <el-form-item label="管理员状态" v-if="formData.root != 1">
                    <el-switch v-model="formData.disable" :active-value="0" :inactive-value="1" />
                </el-form-item>

                <!-- 多处登录 -->
                <el-form-item label="多处登录">
                    <div>
                        <el-switch v-model="formData.multipoint_login" :active-value="1" :inactive-value="0" />
                        <div class="form-tips">允许多人同时在线登录</div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { ref, reactive, computed, shallowRef } from 'vue'
import { ElMessage } from 'element-plus'

import { deptAll } from '@/api/org/department'
import { jobsAll } from '@/api/org/post'
import { adminAdd, adminDetail, adminEdit } from '@/api/perms/admin'
import { roleAll } from '@/api/perms/role'
import { rolegetProvince, rolegetCity } from '@/api/perms/city'
import Popup from '@/components/popup/index.vue'
import AreaPicker from '@/components/area-picker/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const areaIds = ref([])
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑管理员' : '新增管理员'
})

const editArea = ref({
    province_name: '',
    city_name: '',
    area_name: '',
})

const formData = reactive({
    id: '',
    account: '',
    name: '',
    dept_id: [],
    jobs_id: [],
    role_id: [],
    avatar: '',
    password: '',
    password_confirm: '',
    disable: 0,
    multipoint_login: 1,
    root: 0,
    area_ids: [],
    province_id: null,
    city_id: null,
    area_id: null,
    grade: 0
})

// 区域选择相关
const showAreaSelector = ref(false)
const areaOptions = ref<any[]>([])
const cascaderProps = ref({
    multiple: true,
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'name'
})

// 表单验证规则
const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password && value !== formData.password) {
        callback(new Error('两次输入密码不一致!'))
    }
    callback()
}

const roleIdValidator = (rule: object, value: string, callback: any) => {
    if (!formData.root && !formData.role_id.length) {
        callback(new Error('请选择角色'))
    }
    callback()
}

const formRules = reactive({
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ],
    role_id: [
        {
            required: true,
            message: '请选择角色',
            trigger: ['change', 'blur']
        }
    ],
    province_id: [
        {
            required: () => showAreaSelector.value,
            message: '请选择管理区域',
            trigger: ['change']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ] as any[],
    password_confirm: [
        {
            required: true,
            message: '请输入确认密码',
            trigger: ['blur']
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[]
})

// 字典数据
const { optionsData } = useDictOptions<{
    role: any[]
    jobs: any[]
    dept: any[]
}>({
    role: {
        api: roleAll
    },
    jobs: {
        api: jobsAll
    },
    dept: {
        api: deptAll
    }
})

// 处理角色选择变化
const handleRoleChange = async (values: any[]) => {
    console.log(":241241241241241243", values)
    console.log(":241241241241241243", optionsData.role)
    areaIds.value = []
    formData.area_ids = []
    const roleObj = optionsData.role.find(item=>item.id === values)
    formData.grade = roleObj.grade
    console.log(roleObj.grade)
    showAreaSelector.value = !(roleObj.grade === 0 || roleObj.grade === 1);

    /*if (values && values.length > 0 && optionsData.role && Array.isArray(optionsData.role)) {
        // 查找选中角色中的最低级别
        let minGrade = 3
        optionsData.role.forEach(role => {
            // 确保role是对象且有grade属性
            if (role && typeof role === 'object' && 
                values.includes(role.id) && 
                typeof role.grade === 'number' && 
                role.grade < minGrade) {
                minGrade = role.grade
            }
        })
    } else {
    }*/
}

// 加载区域数据
const loadAreaData = async (grade: number) => {
    try {
        // 验证grade参数
        const safeGrade = typeof grade === 'number' ? grade : 0;
        console.log('加载区域数据，grade:', safeGrade);


        let provinces: any[] = []

        // 统一处理API返回数据格式
        if (Array.isArray(result)) {
            provinces = result
        } else if (result && typeof result === 'object') {
            if (result.code === 1 && result.data) {
                provinces = Array.isArray(result.data) ? result.data : [result.data].filter(Boolean)
            } else if (result.id) {
                provinces = [result]
            }
        }

        console.log('获取省份数量:', provinces.length);
        const areaList = []

        for (const province of provinces) {
            if (!province || !province.id) {
                continue; // 跳过无效的省份数据
            }

            try {
                const citiesResult = await rolegetCity({ pid: String(province.id) })
                let cities: any[] = []

                // 统一处理城市数据格式
                if (Array.isArray(citiesResult)) {
                    cities = citiesResult
                } else if (citiesResult && typeof citiesResult === 'object') {
                    if (citiesResult.code === 1 && citiesResult.data) {
                        cities = Array.isArray(citiesResult.data) ? citiesResult.data : [citiesResult.data].filter(Boolean)
                    } else if (citiesResult.id) {
                        cities = [citiesResult]
                    }
                }

                // 确保cities是数组
                if (!Array.isArray(cities)) {
                    cities = [];
                }

                // 根据角色级别构建不同结构的数据
                if (safeGrade === 0) {
                    areaList.push({
                        id: String(province.id),
                        name: province.name || '',
                        children: cities.map((city: any) => ({
                            id: String(city.id || ''),
                            name: city.name || '',
                            children: []
                        }))
                    })
                } else if (safeGrade === 1) {
                    areaList.push(...cities.map((city: any) => ({
                        id: String(city.id || ''),
                        name: city.name || '',
                        children: []
                    })))
                } else if (safeGrade === 2) {
                    areaList.push(...cities.map((county: any) => ({
                        id: String(county.id || ''),
                        name: county.name || '',
                        children: []
                    })))
                } else {
                    // 默认显示省份级别
                    areaList.push({
                        id: String(province.id),
                        name: province.name || '',
                        children: []
                    })
                }
            } catch (error) {
                console.error(`获取城市数据失败 (父ID: ${province.id}):`, error)
            }
        }

        console.log('构建区域数据完成，数量:', areaList.length);
        areaOptions.value = areaList
    } catch (error) {
        console.error('区域数据加载失败:', error)
        ElMessage.error('区域数据加载失败')
    }
}

// 提交表单
const handleSubmit = async () => {
    try {
        console.log('表单验证开始');
        if(mode.value === 'add') {
            const result = await rolegetProvince({})
            formData.province_id = result.id
        }
        formData.city_id = areaIds.value[1] || formData.city_id
        formData.area_id = areaIds.value[2] || formData.area_id
        formData.role_id = [formData.role_id]
        console.log(formData)
        await formRef.value?.validate();
        console.log('表单验证通过');

        // 创建全新的数据对象，避免响应式代理问题
        const submitData: any = {};
        
        // 处理基本字段，确保类型正确
        Object.keys(formData).forEach(key => {
            const value = formData[key];
            if (value !== undefined && value !== null) {
                submitData[key] = value;
            }
        });
        
        // 处理数组字段，确保类型正确
        const arrayFields = ['role_id', 'area_ids', 'dept_id', 'jobs_id'];
        arrayFields.forEach(field => {
            if (!Array.isArray(submitData[field])) {
                submitData[field] = [];
            }
        });
        
        // 编辑模式下处理密码字段
        if (mode.value === 'edit') {
            if (!submitData.password || submitData.password.trim() === '') {
                delete submitData.password;
                delete submitData.password_confirm;
            }
        }
        
        // 修复avatar字段格式
        if (submitData.avatar) {
            submitData.avatar = String(submitData.avatar).replace(/`/g, '').trim();
        }
        
        console.log('提交数据:', JSON.stringify(submitData, null, 2));
        
        // 调用API
        console.log('调用API开始');
        const result = mode.value === 'edit' ? 
            await adminEdit(submitData) : 
            await adminAdd(submitData);
        console.log('result', result)
        // 验证API返回结果
        popupRef.value?.close();
        emit('success');
        ElMessage.success(mode.value === 'edit' ? '编辑成功' : '新增成功');
    } catch (error: any) {
        console.error('操作失败:', error);
        
        // 增强错误处理，提取具体错误信息
        let errorMsg = '';
        if (error?.response?.data?.msg) {
            errorMsg = error.response.data.msg;
        } else if (error?.message) {
            errorMsg = error.message;
        } else if (typeof error === 'string') {
            errorMsg = error;
        } else {
            errorMsg = mode.value === 'edit' ? '编辑失败' : '新增失败';
        }
        
        ElMessage.error(errorMsg);
    }
}

// 打开弹窗
const open = (type = 'add') => {
    mode.value = type
    formData.area_ids = []
    showAreaSelector.value = false
    popupRef.value?.open()
}

// 设置表单数据（编辑模式）
const setFormData = async (row: any) => {
    // 编辑模式下移除密码必填验证
    formRules.password = []
    formRules.password_confirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]

    const data = await adminDetail({
        id: row.id
    })

    Object.keys(formData).forEach(key => {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    })

    editArea.value = data

    // 如果有角色，自动处理区域选择
    formData.role_id = formData.role_id[0]
    handleRoleChange(formData.role_id)

}

// 关闭弹窗
const handleClose = () => {
    formData.area_ids = []
    showAreaSelector.value = false
    emit('close')
}

defineExpose({
    open,
    setFormData
})
</script>